<!-- 新建上传页面组件 -->
<template>
  <div class="main-container">
    <van-nav-bar title="形象上传"  />
    <div class="content-wrapper">
      <!-- <van-image style="position: absolute; top: 0; left: 0; width: 100%; height: 100%;" width="100" height="100"
        src="https://dew-1251587647.cos.ap-guangzhou.myqcloud.com/test/1746600557480_cropped_image.jpg" /> -->
      <van-uploader :after-read="handleFileUpload" accept="image/*" :max-size="5 * 1024 * 1024" @oversize="onOversize"
        :multiple="false" class="uploader-box">
      </van-uploader>

      <van-dialog v-model:show="showCropper" title="图片裁剪" show-cancel-button @confirm="cropImage" @cancel="resetCropper"
        class="cropper-dialog">
        <div class="cropper-wrapper">
          <div class="cropper-container">
            <img ref="cropperImage" :src="previewUrl" alt="裁剪图片" />
          </div>
        </div>
      </van-dialog>
    </div>
  </div>
</template>

<script setup lang="ts">
import { ref, onMounted, nextTick } from 'vue'
import COS from 'cos-js-sdk-v5'
import Cropper from 'cropperjs'
import { showNotify, closeNotify } from 'vant';
import type { UploaderFileListItem as UploaderFileListItemType } from 'vant'
import { useRoute } from 'vue-router'

const cos = new COS({
  SecretId: "AKIDBOOAk6FJ9mALI2YqvlOnyvfBSVKwKTSE",
  SecretKey: "by72kRzLUbU9anncDuQjofQxIQQFqDMH",
})

const previewUrl = ref<string>('')
const type = ref<number>(0);
const selectedFile = ref<File | null>(null)
const isUploading = ref(false)
const showCropper = ref(false)
const cropper = ref<Cropper | null>(null)
const cropperImage = ref<HTMLImageElement | null>(null)
const route = useRoute()

console.log('用户ID:', route.query.user) // 输出 123
console.log('完整查询参数:', route.query)

// 文件类型验证
const isValidImage = (file: File) => {
  const validTypes = ['image/jpeg', 'image/png', 'image/gif', 'image/webp']
  return validTypes.includes(file.type)
}

const isValidAspectRatio = (image: HTMLImageElement) => {
  const targetRatio = 2 / 3;
  const actualRatio = image.width / image.height;
  return Math.abs(actualRatio - targetRatio) < 0.01; // 允许1%的误差
};
const handleFileUpload = (file: UploaderFileListItemType | UploaderFileListItemType[]) => {
  // 新增重置逻辑
  showCropper.value = false;
  cropper.value?.destroy();
  cropper.value = null;
  previewUrl.value = '';
  selectedFile.value = null;

  console.log('文件上传', file)
  // 处理单文件情况
  const fileItem = Array.isArray(file) ? file[0] : file
  if (!fileItem?.file) {
    showNotify({
      message: '文件读取失败',
      type: 'danger'
    })
    return
  }

  if (!isValidImage(fileItem.file)) {
    showNotify({
      message: '仅支持图片文件（JPEG/PNG/GIF/WEBP）',
      type: 'danger'
    })
    return
  }

  const image = new Image()
  image.onload = () => {
    // 无论是否裁剪都设置预览图
    previewUrl.value = URL.createObjectURL(fileItem.file!)

    if (!isValidAspectRatio(image)) {
      showCropper.value = true
      nextTick(initCropper)
    } else {
      // 直接上传
      selectedFile.value = fileItem.file!
      uploadImage()
    }
  }
  image.src = URL.createObjectURL(fileItem.file!)
}

const cropImage = () => {
  if (cropper.value) {
    const canvas = cropper.value.getCroppedCanvas({
      width: 200,
      height: 300
    });

    canvas.toBlob((blob: Blob | null) => {
      if (blob) {
        selectedFile.value = new File([blob], 'cropped_image.jpg', { type: 'image/jpeg' });
        showCropper.value = false;
        // 手动触发上传
        uploadImage();
      }
    }, 'image/jpeg', 0.9);
  }
}

const uploadImage = async () => {
  if (!selectedFile.value) return

  isUploading.value = true

  try {
    const res = await cos.putObject({
      Bucket: "dew-1251587647",
      Region: "ap-guangzhou",
      Key: `test/${Date.now()}_${selectedFile.value.name}`,
      Body: selectedFile.value,
      onProgress: (progress) => {
        console.log(`上传进度：${Math.round(progress.percent * 100)}%`)
      }
    })

    console.log('上传成功', res)
    showNotify({
      message: '上传成功',
      type: 'primary'
    })
    // 重置状态
    previewUrl.value = ''
    selectedFile.value = null
  } catch (error) {
    console.error('上传失败', error)
    showNotify({
      message: '上传失败',
      type: 'danger'
    })
  } finally {
    isUploading.value = false
  }
}

const onOversize = () => {
  showNotify({
    message: '文件大小不能超过5MB',
    type: 'danger'
  })
}

const initCropper = () => {
  if (cropperImage.value) {
    cropper.value = new Cropper(cropperImage.value, {
      aspectRatio: 2 / 3,
      viewMode: 1,
      autoCropArea: 0.8,
      responsive: true,
      checkCrossOrigin: false,
      ready: () => {
        cropper.value?.crop();
      }
    } as Cropper.Options);
  }
}

// 新增重置方法
const resetCropper = () => {
  showCropper.value = false;
  cropper.value?.destroy();
  cropper.value = null;
  previewUrl.value = '';
  selectedFile.value = null;
}
</script>


<style scoped>
.main-container {
  min-height: 100vh;
  display: flex;
  flex-direction: column;
}

.content-wrapper {
  flex: 1;
  display: flex;
  position: relative;
  flex-direction: column;
  align-items: center;
  justify-content: center;
  padding: 20px 20px 100px 20px;
}

.uploader-box {
  max-width: 300px;
}

.upload-button {
  width: 100%;
}

.cropper-dialog {
  --van-dialog-width: 90%;
  --van-dialog-max-width: 1000px;
}

.cropper-wrapper {
  position: relative;
  padding-bottom: 150%;
  /* 保持2:3比例 */
  height: 0;
  overflow: hidden;
}

.cropper-container {
  position: absolute;
  top: 0;
  left: 0;
  width: 100%;
  height: 100%;
}

.cropper-container img {
  max-width: 100%;
  max-height: 70vh;
  object-fit: contain;
}

.preview-actions {
  position: absolute;
  bottom: 50px;
  left: 50%;
  transform: translateX(-50%);
  z-index: 1001;
}

:deep(.van-uploader) {
  margin: 20px 0;
}

:deep(.van-dialog) {
  overflow: visible;
}

:deep(.cropper-view-box) {
  outline: 2px solid #4CAF50;
  border-radius: 4px;
}

:deep(.cropper-line) {
  background-color: rgba(76, 175, 80, 0.3);
}
</style>